package com.web.order.action;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.CommonUtil;
import com.util.JsonUtil;
import com.web.hotel.po.City;
import com.web.hotel.service.HotelService;
import com.web.order.po.OrderPo;
import com.web.order.service.OrderService;
import com.web.order.util.ExportExcel;
import com.web.system.service.UserService;


@Controller @Scope("prototype") 
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "orderAction",results={
	@Result(name = "success", location = "/jsp/charts/chart.jsp"),
})
public class OrderAction extends BaseActionUtil implements ModelDriven<OrderPo>{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4548421583017273629L;

	private OrderPo order;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private HotelService hotelService;
	
	public OrderPo getModel() {
		// TODO Auto-generated method stub
		order = new OrderPo();
		return order;
	}
	
	public void updateOrder() throws Exception {
		
		OrderPo orderPo = orderService.getOrderByOrderId(order.getOrderId());
		orderPo.setBeginTime(order.getBeginTime());
		orderPo.setEndTime(order.getEndTime());
		orderPo.setPrice(order.getPrice());
		orderPo.setOrderContext(order.getOrderContext());
		orderPo.setState(order.getState());
		out.print(orderService.updateOrder(orderPo) ? "1" : "0");
   		out.flush();
   		out.close();
	}
	
	public void deleteOrders() throws Exception {
		String ids = request.getParameter("ids");
		if(CommonUtil.isNotNull(ids)){
			out.print(orderService.deleteOrders(ids));
		} else{
			out.print("-1");
		}
		out.flush();
		out.close();
	}
	
	public void cancleOrders () throws Exception {
		String ids = request.getParameter("ids");
		if(CommonUtil.isNotNull(ids)){
			out.print(orderService.cancleOrders(ids));
		} else{
			out.print("-1");
		}
		out.flush();
		out.close();
	}
	
	public void getOrderByOrderId() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String orderId = request.getParameter("orderId");
		OrderPo orderPo = orderService.getOrderByOrderId(Integer.parseInt(orderId));
        map.put("userId", orderPo.getUser().getUserId());
        map.put("userName", orderPo.getUser().getUserName());
        map.put("hotelId", orderPo.getHotel().getHotelId());
        map.put("hotelName", orderPo.getHotel().getHotelName());
		map.put("order", orderPo);
		out.print(JsonUtil.objectToStr(map,new String[]{"user","hotel"}));
		out.flush();
		out.close();
	}
	
	public void getOrderList() throws Exception {
		
		//分页部分
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		int first = pageSize * (page - 1);
		
		//搜索部分
		String sql = "";
		String orderIdSearch = request.getParameter("orderIdSearch");
		String userNameSearch = request.getParameter("userNameSearch");
		String hotelNameSearch = request.getParameter("hotelNameSearch");
		String price_from = request.getParameter("price_from");
		String price_to = request.getParameter("price_to");
		String date_from = request.getParameter("date_from");
		String date_to = request.getParameter("date_to");
		String stateSearch = request.getParameter("stateSearch");
		String commentSearch = request.getParameter("commentSearch");
		
		if(CommonUtil.isNotNull(orderIdSearch)){
			sql += " and o.orderId like '%"+orderIdSearch+"%'";
		}
		if(CommonUtil.isNotNull(userNameSearch)){
			sql += " and o.user.userName like '%"+userNameSearch+"%'";
		}
		if(CommonUtil.isNotNull(hotelNameSearch)){
			sql += " and o.hotel.hotelName like '%"+hotelNameSearch+"%'";
		}
		if(CommonUtil.isNotNull(price_from)){
			sql += " and o.price >= '" + price_from + "'";
		}
		if(CommonUtil.isNotNull(price_to)){
			sql +=" and o.price <= '" + price_to + "'";
		}
		if(CommonUtil.isNotNull(date_from)){
			sql += " and o.createTime >= '" + date_from + "'";
		}
		if(CommonUtil.isNotNull(date_to)){
			sql +=" and o.createTime <= '" + date_to + "'";
		}
		if(CommonUtil.isNotNull(stateSearch)){
			sql +=" and o.state = '" + stateSearch + "'";
		}
		if(CommonUtil.isNotNull(commentSearch)){
			sql += " and o.comment like '%"+commentSearch+"%'";
		}
		
		//组合最终sql语句
		StringBuffer queryStringBuffer = new StringBuffer();
		queryStringBuffer.append("FROM OrderPo as o");
		queryStringBuffer.append(" left outer join fetch o.user as u");
		queryStringBuffer.append(" left outer join fetch o.hotel as h");
		queryStringBuffer.append(" where 1=1 ");
		queryStringBuffer.append(sql);
		queryStringBuffer.append(" ORDER BY o.state desc");
        List<OrderPo> orders = orderService.getOrderList(queryStringBuffer.toString(), first, pageSize);
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        if(null != orders && orders.size() > 0) {
            for (int i = 0; i < orders.size(); i++) {
            	Map<String, Object> map = new HashMap<String, Object>();
            	map.put("orderId", orders.get(i).getOrderId());
            	map.put("orderContext", orders.get(i).getOrderContext());
            	map.put("price", orders.get(i).getPrice());
            	map.put("state", orders.get(i).getState());
            	map.put("beginTime", orders.get(i).getBeginTime());
            	map.put("endTime", orders.get(i).getEndTime());
            	map.put("createTime", orders.get(i).getCreateTime());
            	map.put("userId", orders.get(i).getUser().getUserId());
            	map.put("userName", orders.get(i).getUser().getUserName());
            	map.put("hotelId", orders.get(i).getHotel().getHotelId());
            	map.put("hotelName", orders.get(i).getHotel().getHotelName());
            	map.put("comment", orders.get(i).getComment());
            	userList.add(map);
    		}
        }

        Map<String, Object> jsonMap = new HashMap<String, Object>();
        int total = orderService.total(sql);
        jsonMap.put("total", total);
        jsonMap.put("rows", userList);
        out.print(JsonUtil.objectToStr(jsonMap));
        out.flush();
        out.close();
	}
	
	public void exportExcel() throws Exception {
		String ids = request.getParameter("ids");
		//搜索部分
		String sql = "";
		String orderIdSearch = request.getParameter("orderIdSearch");
		String userNameSearch = request.getParameter("userNameSearch");
		String hotelNameSearch = request.getParameter("hotelNameSearch");
		String price_from = request.getParameter("price_from");
		String price_to = request.getParameter("price_to");
		String date_from = request.getParameter("date_from");
		String date_to = request.getParameter("date_to");
		String stateSearch = request.getParameter("stateSearch");
		String commentSearch = request.getParameter("commentSearch");
		if(CommonUtil.isNotNull(ids)){
			sql += " and o.orderId in ("+ids+")";
		} else{
			if(CommonUtil.isNotNull(orderIdSearch)){
				sql += " and o.orderId like '%"+orderIdSearch+"%'";
			}
			if(CommonUtil.isNotNull(userNameSearch)){
				sql += " and o.user.userName like '%"+userNameSearch+"%'";
			}
			if(CommonUtil.isNotNull(hotelNameSearch)){
				sql += " and o.hotel.hotelName like '%"+hotelNameSearch+"%'";
			}
			if(CommonUtil.isNotNull(price_from)){
				sql += " and o.price >= '" + price_from + "'";
			}
			if(CommonUtil.isNotNull(price_to)){
				sql +=" and o.price <= '" + price_to + "'";
			}
			if(CommonUtil.isNotNull(date_from)){
				sql += " and o.createTime >= '" + date_from + "'";
			}
			if(CommonUtil.isNotNull(date_to)){
				sql +=" and o.createTime <= '" + date_to + "'";
			}
			if(CommonUtil.isNotNull(stateSearch)){
				sql +=" and o.state = '" + stateSearch + "'";
			}
			if(CommonUtil.isNotNull(commentSearch)){
				sql += " and o.comment like '%"+commentSearch+"%'";
			}
		}
		
		List<List<String>> orderList = orderService.getExportOrderList(sql);
		response.reset();
		HttpServletResponse response1 = ServletActionContext.getResponse();
		OutputStream os = null;
		try {
			String filename = "order_" + String.valueOf((new Date()).getTime()) + ".xls";
			os = response1.getOutputStream();
			response1.reset();
			response1.setHeader("Content-disposition", "attachment;  filename="
					+ filename);
			response1.setContentType("application/msexcel");
			ExportExcel exportExcel = new ExportExcel();
			exportExcel.writeExcel(os, orderList);
			exportExcel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.print(1);
		out.flush();
		out.close();
	}
	
	public void getCityName(){
		List<City> cities = orderService.getCity();
		out.print(JsonUtil.objectToStr(cities));
		out.flush();
		out.close();
	}
	
	
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		
		Map<String,Object> mapJson = new HashMap<String, Object>();
		
		String cityId = "福州市";
		Integer hotelId = new Integer(3);
		String cityId_param = request.getParameter("cityId");
		String hotelId_param = request.getParameter("hotelId");
		if(CommonUtil.isNotNull(cityId_param)){
			cityId = cityId_param;
		}
		if(CommonUtil.isNotNull(hotelId_param)){
			hotelId  = Integer.parseInt(hotelId_param);
		}
		request.setAttribute("cityId", cityId);
		request.setAttribute("hotelId", hotelId);
		
		//------------------------今日下单情况-------------------------//
		
		List<?> sourceDataList0 = null;
		StringBuffer sqlBuffer0 = new StringBuffer();
		sqlBuffer0.append(" select DATE_FORMAT(createTime,'%c') as row , "); 
		sqlBuffer0.append(" sum(case when state = 4 then 1 else 0 end) as success,");
		sqlBuffer0.append("  (count(*) - sum(case when state = 4 then 1 else 0 end)) as fail,");
		sqlBuffer0.append("  sum(case when state = 4 then price else 0 end) as price");
		sqlBuffer0.append("  from t_order ");
		sqlBuffer0.append("  where DATE_FORMAT(createTime,'%y%c%d') = (DATE_FORMAT(NOW(),'%y%c%d') ) and hotelId =");
		sqlBuffer0.append(hotelId);
		sourceDataList0 = orderService.getChart(sqlBuffer0.toString() , 4);
		if(sourceDataList0 != null && sourceDataList0.size() > 0){
				// 数据解析
				Object[] item = (Object[]) sourceDataList0.get(0);
				String success = item[1] + "" ;
				String fail =  item[2] + "";
				String price =  item[3] + "";
				request.setAttribute("success", CommonUtil.isNotNull(success) ? success : "0");
				request.setAttribute("fail", CommonUtil.isNotNull(fail) ? fail : "0");
				request.setAttribute("price", CommonUtil.isNotNull(price) ? price : "0");
		} else {
				request.setAttribute("success", 0);
				request.setAttribute("fail", 0);
				request.setAttribute("price", 0);
		}
		
		//-------------------------昨日下单情况-------------------------//
		
		List<?> sourceDataList1 = null;
		Map<String, Object> chartData1 = new HashMap<String, Object>();

		StringBuffer sqlBuffer1 = new StringBuffer();
		sqlBuffer1.append(" select DATE_FORMAT(createTime,'%c') as row , "); 
		sqlBuffer1.append(" sum(case when state = 4 then 1 else 0 end) as success,");
		sqlBuffer1.append("  (count(*) - sum(case when state = 4 then 1 else 0 end)) as fail");
		sqlBuffer1.append("  from t_order ");
		sqlBuffer1.append("  where DATE_FORMAT(createTime,'%y%c') = (DATE_FORMAT(NOW(),'%y%c') ) and");
		sqlBuffer1.append("  DATE_FORMAT(createTime,'%d') = (DATE_FORMAT(NOW(),'%d') - 1) and hotelId = ");
		sqlBuffer1.append(hotelId);
		
		sourceDataList1 = orderService.getChart(sqlBuffer1.toString() , 3);
		List<Map<String,Object>> seriesDataList1 = new ArrayList<Map<String,Object>>();
		if(sourceDataList1 != null && sourceDataList1.size() > 0){
				// 数据解析
				Object[] item = (Object[]) sourceDataList1.get(0);
				Integer success = (Integer) item[1] ;
				Integer fail = (Integer) item[2];
				Map<String,Object> s = new HashMap<String, Object>();
				Map<String,Object> f = new HashMap<String, Object>();
				s.put("name", "成功下单");
				s.put("value", success);
				f.put("name", "失败下单");
				f.put("value", fail);
				seriesDataList1.add(s);
				seriesDataList1.add(f);
		}
		chartData1.put("series", seriesDataList1);
		mapJson.put("chart1", chartData1);
		
		
		//---------------------------2016年到当前月订单成功/失败折线图--------//
		List<?> sourceDataList4 = null;
		List<String> xAxisList4 = new ArrayList<String>();
		Map<String, Object> chartData4 = new HashMap<String, Object>();

		StringBuffer sqlBuffer4 = new StringBuffer();
		sqlBuffer4.append(" select DATE_FORMAT(createTime,'%c') as row ,"); 
		sqlBuffer4.append(" sum(case when state = 4 then 1 else 0 end) as success,");
		sqlBuffer4.append(" (count(*) - sum(case when state = 4 then 1 else 0 end)) as fail");
		sqlBuffer4.append("  from t_order");
		sqlBuffer4.append("  where DATE_FORMAT(createTime,'%y') = (DATE_FORMAT(NOW(),'%y')) and hotelId =");
		sqlBuffer4.append(hotelId);
		sqlBuffer4.append("  group by row");
		sourceDataList4 = orderService.getChart(sqlBuffer4.toString() , 3);
		List<Integer> seriesDataList40 = new ArrayList<Integer>();
		List<Integer> seriesDataList41 = new ArrayList<Integer>();
		//当前月份
		int nowMonth = Integer.parseInt(new SimpleDateFormat("MM" ).format(new Date()));
		for (int i = 1; i <= nowMonth; i++) {
			xAxisList4.add(i + "月");
			seriesDataList40.add(0);
			seriesDataList41.add(0);
		}
		if(sourceDataList4 != null && sourceDataList4.size() > 0){
			for (int i = 0; i < sourceDataList4.size(); i++) {
				// 数据解析
				Object[] item = (Object[]) sourceDataList4.get(i);
				Integer index = (Integer) item[0] ;
				Integer success = (Integer) item[1];
				seriesDataList40.set(index - 1, success);
				Integer fail = (Integer) item[2];
				seriesDataList41.set(index - 1, fail);
			}
		}
		chartData4.put("xAxis", xAxisList4);
		chartData4.put("series0", seriesDataList40);
		chartData4.put("series1", seriesDataList41);
		mapJson.put("chart4", chartData4);
		
		
		//----------------------------2015年销售量------------------------//
		List<?> sourceDataList6 = null;
		List<String> xAxisList6 = new ArrayList<String>();
		Map<String, Object> chartData6 = new HashMap<String, Object>();

		StringBuffer sqlBuffer6 = new StringBuffer();
		sqlBuffer6.append(" select DATE_FORMAT(createTime,'%c') as row , count(*) as count from t_order"); 
		sqlBuffer6.append(" where DATE_FORMAT(createTime,'%y') = (DATE_FORMAT(NOW(),'%y') - 1) and hotelId =");
		sqlBuffer6.append(hotelId);
		sqlBuffer6.append("  group by row");
		sourceDataList6 = orderService.getChart(sqlBuffer6.toString() , 2);
		List<Integer> seriesDataList6 = new ArrayList<Integer>();
		for (int i = 1; i <= 12; i++) {
			xAxisList6.add(i + "月");
			seriesDataList6.add(0);
		}
		if(sourceDataList6 != null && sourceDataList6.size() > 0){
			for (int i = 0; i < sourceDataList6.size(); i++) {
				// 数据解析
				Object[] item = (Object[]) sourceDataList6.get(i);
				Integer index = (Integer) item[0] ;
				Integer count = (Integer) item[1];
				seriesDataList6.set(index - 1, count);
			}
		}
		chartData6.put("xAxis", xAxisList6);
		chartData6.put("series", seriesDataList6);
		mapJson.put("chart6", chartData6);
		
		//-----------------------------2015年销售量金额---------------------//
		List<?> sourceDataList7 = null;
		List<String> xAxisList7 = new ArrayList<String>();
		Map<String, Object> chartData7 = new HashMap<String, Object>();
		StringBuffer sqlBuffer7 = new StringBuffer();
		sqlBuffer7.append(" select DATE_FORMAT(createTime,'%c') as row , sum(price) as count from t_order"); 
		sqlBuffer7.append(" where DATE_FORMAT(createTime,'%y') = (DATE_FORMAT(NOW(),'%y') - 1) and hotelId =");
		sqlBuffer7.append(hotelId);
		sqlBuffer7.append("  group by row");
		sourceDataList7 = orderService.getChart(sqlBuffer7.toString() , 2);
		
		List<Integer> seriesDataList7 = new ArrayList<Integer>();
		xAxisList7 = new ArrayList<String>();
		for (int i = 1; i <= 12; i++) {
			xAxisList7.add(i + "月");
			seriesDataList7.add(0);
		}
		if(sourceDataList7 != null && sourceDataList7.size() > 0){
			for (int i = 0; i < sourceDataList7.size(); i++) {
				// 数据解析
				Object[] item = (Object[]) sourceDataList7.get(i);
				Integer index = (Integer) item[0] ;
				Integer count = (Integer) item[1];
				seriesDataList7.set(index - 1, count);
			}
		}
		chartData7.put("xAxis", xAxisList7);
		chartData7.put("series", seriesDataList7);
		mapJson.put("chart7", chartData7);
		
		request.setAttribute("data", JsonUtil.objectToStr(mapJson));
		return SUCCESS;
	}
}
